package com.cqhz.quwan.ui.buy

import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v4.app.Fragment
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.BettingItem
import com.cqhz.quwan.model.Lottery
import com.cqhz.quwan.model.LotteryList
import com.cqhz.quwan.service.API
import com.cqhz.quwan.ui.base.AbsAdapter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.widget.AutoHeightFormatGridView
import com.cqhz.quwan.util.PayEventObserver
import com.cqhz.quwan.util.PayEventSubscribe
import com.cqhz.quwan.util.startRotateAnimation
import com.cqhz.quwan.util.v

class BettingMachineActivity : GoBackActivity(),PayEventSubscribe {
    override fun doPayFinish() {
        finish()
    }

    private val downwardIv by v<ImageView>(R.id.iv_downward)
    private val titleTextWrap by v<LinearLayout>(R.id.title_text_wrap)
    private val bettingTitleBar by v<RelativeLayout>(R.id.betting_title_bar)
    private var currentFragment: Fragment? = null
    private var currentBetIndex = 0
    private val addedFragment = ArrayList<Fragment>()
    private var isOpen = false
    private var betTypePopup: PopupWindow? = null
    private val betTypes = ArrayList<String>()
    private val betTypeFragments = ArrayList<Fragment>()
    private val titles = ArrayList<String>()
    private lateinit var dropdownMenu:PopupWindow
    private val dropdownMenuSize = IntArray(2)
    var currentLotteryId:String? = null
    var isReset = false
    var resetIndex = -1
    var currentPeriodNum:String? = null
    var currentLotteryName:String? = null
    override fun titleBarText(): String? {
        return "双色球"
    }

    override fun onTitleTextClickFlag(): Boolean {
        return false
    }
    override fun titleBarRightIconResId(): Int? {
        return R.drawable.icon_more
    }
    override fun onTitleBarRightClick(v:View) {
        val location = IntArray(2)
        v.getLocationOnScreen(location)
        dropdownMenu.showAsDropDown(v)
    }
    override fun layout(): Int {
        return R.layout.activity_betting_machine
    }

    private fun showPopup(){
        isOpen = if (isOpen) {
            downwardIv.startRotateAnimation(180, 180, 250)
            if (betTypePopup?.isShowing!!) {
                betTypePopup?.dismiss()
            }
            false
        } else {
            downwardIv.startRotateAnimation(0, 180, 250)
            showBetTypePopupWindow(betTypes)
            true
        }

    }


    private fun titleTextWrapInit() {
        if(betTypeFragments.size<2){
            downwardIv.visibility = View.GONE
        }
        titleTextWrap.setOnClickListener {
            if(betTypeFragments.size>1){
                showPopup()
            }
        }
    }

    private fun showFragment(frag:Fragment){
        if(frag == currentFragment){
            return
        }
        val transaction = supportFragmentManager.beginTransaction()
        if(currentFragment != null){
            transaction.hide(currentFragment)
        }
        if(frag.isAdded){
            transaction.show(frag)
        } else if(!addedFragment.contains(frag)){
            transaction.add(R.id.betting_content,frag)
            addedFragment.add(frag)
        }
        transaction.commitAllowingStateLoss()
        currentFragment = frag
    }
    private fun lotteryList(los: LotteryList.() -> Unit) {
        val wrapper = LotteryList()
        wrapper.los()
        val l = wrapper.data.find {
            it.id == currentLotteryId
        }
        if(l != null){
            currentLotteryName = l.name
            betTypes.clear()
            betTypeFragments.clear()
            betTypes.addAll(l.betTypes)
            betTypeFragments.addAll(l.betTypeFragments)
            titles.addAll(l.genTitles())
            showFragment(betTypeFragments[currentBetIndex])
            setTitleBarText(titles[currentBetIndex])
        }
    }

    override fun initView() {
        PayEventObserver.register(this)
        isReset = intent.getBooleanExtra(KeyContract.IsReset,false)
        resetIndex = intent.getIntExtra(KeyContract.ResetIndex,-1)
        currentPeriodNum = intent.getStringExtra(KeyContract.PeriodNum)
        currentLotteryId = intent.getStringExtra(KeyContract.LotteryId)
        val item = intent.getSerializableExtra(KeyContract.BettingItem) as? BettingItem
        dropdownMenu = createPopupWindow()
        val betBits = item?.betBits
        currentBetIndex = when(item?.typeId){
            Lottery.TYPE_LOTTO_NORMAL -> 0
            Lottery.TYPE_LOTTO_COURAGE -> 1
            Lottery.TYPE_NUM_ZX -> 0
            Lottery.TYPE_NUM_Z3_SINGLE -> 1
            Lottery.TYPE_NUM_Z3_MULTI -> when(currentLotteryId){
                "12" -> 2
                "16" -> 1
                else -> 0
            }
            Lottery.TYPE_NUM_Z6 -> when(currentLotteryId){
                "12" -> 3
                "16" -> 2
                else -> 0
            }
            else -> 0
        }
        lotteryList {
            lottery {
                id = "11"
                name = "双色球"
                lotto {
                    redBalls {
                        selected = item?.redBalls
                        dmSelected = item?.redDMSelected()
                        tmSelected = item?.redTMSelected()
                        label = "红球"
                        range = (1..33).toList()
                        selectMin = 6
                        selectMax = 33
                        selectDMMin = 1
                        selectDMMax = 4
                        selectTMMin = 2
                        selectTMMax = 16

                        tip = ""
                        dmLabel = "胆码"
                        dmTip = "我认为必出的红球，可选1-4个"
                        tmLabel = "拖码"
                        tmTip = "我认为可能出的红球，可选2-16个"
                    }
                    blueBalls {
                        selected = item?.blueBalls
                        dmSelected = item?.blueDMSelected()
                        tmSelected = item?.blueTMSelected()
                        label = "蓝球"
                        range = (1..16).toList()
                        selectMin = 1
                        selectMax = 16
                        tip = "至少选1个"
                    }
                }
            }
            lottery {
                id = "14"
                name = "大乐透"
                lotto {
                    redBalls {
                        selected = item?.redBalls
                        dmSelected = item?.redDMSelected()
                        tmSelected = item?.redTMSelected()
                        label = "前区"
                        range = (1..35).toList()
                        selectMin = 5
                        selectMax = 20
                        selectDMMin = 1
                        selectTMMin = 2
                        selectDMMax = 4
                        selectTMMax = 16
                        tip = ""
                        dmLabel = "前区胆码"
                        dmTip = "我认为必出的号，最多4个"
                        tmLabel = "前区拖码"
                        tmTip = "我认为可能出的号，可选2-16个"
                    }
                    blueBalls {
                        selected = item?.blueBalls
                        dmSelected = item?.blueDMSelected()
                        tmSelected = item?.blueTMSelected()
                        label = "后区"
                        range = (1..12).toList()
                        selectMin = 2
                        selectDMMin = 1
                        selectTMMin = 2
                        selectMax = 16
                        selectDMMax = 1
                        tip = ""
                        dmLabel = "后区胆码"
                        dmTip = "我认为必出的号，最多1个"
                        tmLabel = "后区拖码"
                        tmTip = "我认为可能会出的号，至少2个"
                    }
                }
            }
            lottery {
                name = "福彩3D"
                id = "12"
                num {
                    betMethod {
                        name = "直选"
                        id = "1"
                        tipLabel = "按位猜中3个开奖号码即奖 <font color='#EC0411'>1040</font> 元"
                        bitLine {
                            label = "百位"
                            selectMin = 1
                            selected = if(betBits != null && betBits.size==3){
                                betBits[0]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "十位"
                            selectMin = 1
                            selected = if(betBits != null && betBits.size==3){
                                betBits[1]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "个位"
                            selectMin = 1
                            selected = if(betBits != null && betBits.size==3){
                                betBits[2]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                    }
                    betMethod {
                        name = "组三单式"
                        id = "2"
                        tipLabel = "选1个重号和1个单号，猜对开奖号即中 <font color='#EC0411'>346</font> 元"
                        linkages = arrayListOf(0,1)
                        bitLine {
                            label = "重号"
                            selectMax = 1
                            selected =if(betBits != null && betBits.size==2){
                                betBits[0]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "单号"
                            selected =if(betBits != null && betBits.size==2){
                                betBits[1]
                            }else{
                                null
                            }
                            selectMax = 1
                            nums = (0..9).toList()
                        }
                    }
                    betMethod {
                        name = "组三复式"
                        id = "3"
                        tipLabel = "至少选2个号，猜对开奖号（顺序不限）即可中 <font color='#EC0411'>346</font> 元"
                        bitLine {
                            label = "选号"
                            selectMin = 2
                            selected =if(betBits != null && betBits.size==1){
                                betBits[0]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                    }
                    betMethod {
                        name = "组六"
                        id = "4"
                        tipLabel = "至少选3个号，猜对开奖号（顺序不限）即中 <font color='#EC0411'>173</font> 元"
                        bitLine {
                            label = "选号码"
                            selectMin = 3
                            selected =if(betBits != null && betBits.size==1){
                                betBits[0]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                    }
                }
            }
            lottery {
                id = "16"
                name = "排列3"
                num {
                    betMethod {
                        id = "1"
                        name = "直选"
                        tipLabel = "按位猜中3个开奖号即奖 <font color='#EC0411'>1040</font> 元"
                        bitLine {
                            label = "百位"
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "十位"
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "个位"
                            nums = (0..9).toList()
                        }
                    }
                    betMethod {
                        id = "3"
                        name = "组三"
                        tipLabel = "至少选2个号，猜对开奖号（顺序不限）即中 <font color='#EC0411'>346</font> 元"
                        bitLine {
                            label = "百位"
                            selectMin = 2
                            nums = (0..9).toList()
                        }
                    }
                    betMethod {
                        id = "4"
                        name = "组六"
                        tipLabel = "至少选3个号，猜对开奖号（顺序不限）即中 <font color='#EC0411'>173</font> 元"
                        bitLine {
                            selectMin = 3
                            label = "选号码"
                            nums = (0..9).toList()
                        }
                    }
                }
            }
            lottery {
                id = "15"
                name = "七星彩"
                num {
                    betMethod {
                        id = "1"
                        name = "直选"
                        bitLine {
                            label = "第一位"
                            selected =if(betBits != null && betBits.size==7){
                                betBits[0]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "第二位"
                            selected =if(betBits != null && betBits.size==7){
                                betBits[1]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "第三位"
                            selected =if(betBits != null && betBits.size==7){
                                betBits[2]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "第四位"
                            selected =if(betBits != null && betBits.size==7){
                                betBits[3]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "第五位"
                            selected =if(betBits != null && betBits.size==7){
                                betBits[4]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "第六位"
                            selected =if(betBits != null && betBits.size==7){
                                betBits[5]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                        bitLine {
                            label = "第七位"
                            selected =if(betBits != null && betBits.size==7){
                                betBits[6]
                            }else{
                                null
                            }
                            nums = (0..9).toList()
                        }
                    }
                }
            }
        }

        titleTextWrapInit()
    }

    private fun showBetTypePopupWindow(types: List<String>) {
        if (betTypePopup == null) {
            val view = layoutInflater.inflate(R.layout.layout_bet_type, null, false)
            val ahGridView = view.findViewById<AutoHeightFormatGridView>(R.id.ahGridView)
            val adapter = object : AbsAdapter<String>(this, R.layout.item_bet_type) {
                val checked = ArrayList<Int>()
                init {
                    checked.add(0)
                }
                @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
                override fun handlerViewHolder(viewHolder: ViewHolder, position: Int, itemData: String?) {
                    val tv = viewHolder.find<TextView>(R.id.bet_type_text)
                    if (checked.contains(position)){
                        tv.background = context.getDrawable(R.drawable.sp_stroke_red_xx1_5)
                        tv.setTextColor((0xFFFFFFFF).toInt())
                    }else{
                        tv.background = context.getDrawable(R.drawable.sp_stroke_red_x1_5)
                        tv.setTextColor((0xFFEC0411).toInt())
                    }
                    tv.text = itemData ?: ""
                    viewHolder.setItemClick {
                        checked.clear()
                        checked.add(position)
                        notifyDataSetChanged()
                        showFragment(betTypeFragments[position])
                        showPopup()
                        setTitleBarText(titles[position])
                    }
                }
            }
            if (types.size > 2) {
                ahGridView.numColumns = 2
            } else {
                ahGridView.numColumns = 2
            }
            ahGridView.adapter = adapter
            adapter.setData(types)
            betTypePopup = PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            betTypePopup!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            betTypePopup!!.isOutsideTouchable = false
            betTypePopup!!.isTouchable = true
        }
        betTypePopup!!.showAsDropDown(bettingTitleBar, 0, 0)

    }

    private fun createPopupWindow():PopupWindow{
        val view = layoutInflater.inflate(R.layout.layout_drapdown_more, null,false)
        val lishi = view.findViewById<TextView>(R.id.dropdown_lishi)
        val wanfa = view.findViewById<TextView>(R.id.dropdown_wanfa)
        lishi.setOnClickListener {
            dropdownMenu.dismiss()
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title,"历史开奖")
            val url = "${API.LishiKaiJiang}?id=$currentLotteryId"
            intent.putExtra(KeyContract.Url, url)
            startActivity(intent)
        }
        wanfa.setOnClickListener {
            dropdownMenu.dismiss()
            val intent = Intent(this, WebViewActivity::class.java)
            intent.putExtra(KeyContract.Title,"玩法说明")
            val url = "${API.Wanfa}?query=$currentLotteryId"
            intent.putExtra(KeyContract.Url,url)
            startActivity(intent)
        }
        view.measure(View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED)
        dropdownMenuSize[0] =view.measuredWidth
        dropdownMenuSize[1] =view.measuredHeight
        val window = PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        window.isOutsideTouchable = true
        window.isTouchable = true
        return window
    }
}